package com.johnny.xia.util.http;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.net.ssl.SSLContext;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;

import com.gargoylesoftware.htmlunit.javascript.host.fetch.Request;
import com.johnny.xia.util.base.ValidatorUtil;

public class HttpClientUtil {

    private static final String APPLICATION_JSON = "application/json";

    private static final String CONTENT_TYPE_TEXT_JSON = "text/json";

    private static final String CHARACTER_UTF8 = "UTF-8";

	/**
	 * http post 請求
	 * @param command
	 * 			请求参数对象，包含URL，param。具体请参见HttpClientCommand
	 * @return
	 * 		返回字符串，如果请求出错，返回null
	 * @throws KeyStoreException
	 * @throws NoSuchAlgorithmException
	 * @throws KeyManagementException
	 */
	public static HttpReturnCommand post(HttpClientCommand command) throws KeyStoreException, KeyManagementException, NoSuchAlgorithmException {

		HttpReturnCommand result = new HttpReturnCommand();

//		 KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
//
//		 SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
//
//        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1.2" }, null,
//                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
//
//		//创建httpClient 请求对象。
//		CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();


//		SSLContext sslContext = SSLContext.getInstance("TLS");
//		SSLContext sslContext = SSLContexts.custom().useProtocol("TLSv1.2").build();
//
		SSLContext sslContext = SSLContextBuilder.create().useProtocol("TLSv1.2").build();

		CloseableHttpClient httpclient = HttpClients.custom().setSSLContext(sslContext).build();

//		CloseableHttpClient httpclient = HttpClients.createDefault();

		HttpPost httppost = new HttpPost(command.getUrl());


		List<NameValuePair> formparams = new ArrayList<NameValuePair>();

		StringBuffer strBuf = new StringBuffer(command.getUrl()).append("?");

		//构建httpClient 请求参数。
		if(ValidatorUtil.isNotNullOrEmpty(command.getParamMap())){
			Map<String,String> paramMap = command.getParamMap();
			for(Entry<String, String> entry : paramMap.entrySet()){
				formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));

				strBuf.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
			}
		}

		System.out.println("post info url : "+strBuf.toString());


		UrlEncodedFormEntity uefEntity;
		try {
			uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
			httppost.setEntity(uefEntity);
			CloseableHttpResponse response = httpclient.execute(httppost);
			try {
				HttpEntity entity = response.getEntity();
				result.setStatus(response.getStatusLine().getStatusCode());
				if (entity != null) {
					result.setContent(EntityUtils.toString(entity, "UTF-8"));
				}
				return result;

			} finally {
				response.close();
			}

		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	   public static HttpReturnCommand post(String url, String jsonData) {

	        HttpReturnCommand result = new HttpReturnCommand();
	        result.setStatus(-1);
	        CloseableHttpClient httpclient = HttpClients.createDefault();
	        HttpPost httppost = new HttpPost(url);

	        StringEntity se = new StringEntity(jsonData, CHARACTER_UTF8);
//	        se.setContentType(CONTENT_TYPE_TEXT_JSON);
	        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON));

	        httppost.setEntity(se);
	        CloseableHttpResponse response;
	        try {
	            response = httpclient.execute(httppost);
	            HttpEntity entity = response.getEntity();
	            result.setStatus(response.getStatusLine().getStatusCode());
	            if (entity != null) {
	                result.setContent(EntityUtils.toString(entity, "UTF-8"));
	            }
	            response.close();
	            return result;
	        } catch (IOException e) {
	        	e.printStackTrace();
	            result.setContent(e.getMessage());
	        } finally {
	            try {
	                httpclient.close();
	            } catch (IOException e) {
	                e.printStackTrace();
	            }
	        }

	        return result;
	    }


	/*public static String sslPost(String url,Map<String,String> map,String charset){
		HttpClient httpClient = null;
		HttpPost httpPost = null;
		String result = null;
		try{
			httpClient = new SSLClient();
			httpPost = new HttpPost(url);
			//设置参数
			List<NameValuePair> list = new ArrayList<NameValuePair>();
			Iterator iterator = map.entrySet().iterator();
			while(iterator.hasNext()){
				Entry<String,String> elem = (Entry<String, String>) iterator.next();
				list.add(new BasicNameValuePair(elem.getKey(),elem.getValue()));
			}
			if(list.size() > 0){
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,charset);
				httpPost.setEntity(entity);
			}
			HttpResponse response = httpClient.execute(httpPost);
			if(response != null){
				HttpEntity resEntity = response.getEntity();
				if(resEntity != null){
					result = EntityUtils.toString(resEntity,charset);
				}
			}
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return result;
	}*/




	/**
	 * httpclient get请求
	 * @param command
	 * @return
	 * 		返回请求相应字符串，
	 */
	public static HttpReturnCommand get(HttpClientCommand command){

		HttpReturnCommand result = new HttpReturnCommand();

		CloseableHttpClient httpclient = HttpClients.createDefault();
		try {

			StringBuffer urlBf = new StringBuffer(command.getUrl());
			if(ValidatorUtil.isNotNullOrEmpty(command.getParamMap())){
				urlBf.append("?");
				for(Entry<String, String> entry : command.getParamMap().entrySet()){
					urlBf.append(entry.getKey())
						.append("=")
						.append(entry.getValue())
						.append("&");
				}

				command.setUrl(urlBf.substring(0, urlBf.length()-1));
			}


			// 创建httpget.
			HttpGet httpget = new HttpGet(command.getUrl());

			// 执行get请求.
			CloseableHttpResponse response = httpclient.execute(httpget);
			try {
				// 获取响应实体
				HttpEntity entity = response.getEntity();
				result.setStatus(response.getStatusLine().getStatusCode());
				if (entity != null) {
					result.setContent(EntityUtils.toString(entity));
				}
				return result;
			} finally {
				response.close();
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭连接,释放资源
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return null;
	}

	public static void main(String[] args) {
		HttpClientCommand command = new HttpClientCommand("https://www.philips.com.cn/api/v1/user/requestAuthorizationSmsCode");
		command.putParam("phonenumber","8615551615602");
		command.putParam("locale","zh_CN");
		command.putParam("provider","JANRAIN-CN");

		try {
			HttpReturnCommand ret = post(command);
			System.out.println(ret.toString());
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}
